<?php

namespace common\models;

use Yii;
use common\helpers\Util;

/**
 * This is the model class for table "UserEvaluate".
 */
class UserEvaluate extends ActiveRecord {

    // 星级上限
    const StartLimit = 5;
    
    // only define rules for those attributes that
    // will receive user inputs.
    public function rules()
    {
        return [
            [['user_id', 'employment_id', 'evaluator', 'communicate', 'originality', 'efficiency', 'major'], 'required'],
            [['user_id', 'employment_id', 'evaluator', 'communicate', 'originality', 'efficiency', 'major'], 'integer'],
            [['remark'], 'string', 'max' => 255],
        ];
    }
    /**
     * 字段名称
     * @return array
     */
    public function attributeLabels()
    {
        return [
            'user_id' => '用户编号',
            'employment_id' => '服务编号',
            'evaluator' => '评价人',
            'communicate' => '沟通',
            'originality' => '创意',
            'efficiency' => '效率',
            'major' => '专业',
            'remark' => '评价',
        ];
    }
    /**
     * update & insert data check config for html
     * @param $type string 操作类型
     * @param $encodeJson boolean 是否转成JSON字符串
     * @return array
     */
    public static function flyer($type = 'insert')
    {
        return [
            'param' => [
                'employment_id' => ['服务编号', ['int', 'required']],
                'communicate' => ['沟通', ['int', 'let' => static::StartLimit, 'required']],
                'originality' => ['创意', ['int', 'let' => static::StartLimit, 'required']],
                'efficiency' => ['效率', ['int', 'let' => static::StartLimit, 'required']],
                'major' => ['专业', ['int', 'let' => static::StartLimit, 'required']],
                'remark' => ['评论语', ['maxlength' => 255, 'required']],
            ],
        ];
    }
    
    /**
     * 获取评级对应的用户
     * @return object
     */
    public function getUser()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }
    
    /**
     * 获取评价人
     * @return object
     */
    public function getEmployer()
    {
        return $this->hasOne(User::className(), ['id' => 'evaluator']);
    }

    /**
     * 添加评价
     * @param $param array 数据数组
     * @return boolean
     */
    public static function creator($param)
    {
        $evaluate = new static();
        // evaluator 为 0 时表示系统默认评价
        $param['evaluator'] = Yii::$app->isLogin() ? Yii::$app->user->id : 0;
        $evaluate->load([static::className() => $param], static::className());
        return $evaluate->transaction(function($db) use ($evaluate) {
            if( ! $evaluate->save()) {
                throw new \Exception('create user evaluate error');
            }
            // 重新计算用户的星级
            if( ! $evaluate->user->calculateStar()) {
                throw new Exception('calculate star error');
            }
            return true;
        });
    }
}